package test.com.pzh.mall.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author Ray
 * @date 2018/1/11.
 */
public class HttpUtils {
    private static final Logger log = LoggerFactory.getLogger(HttpUtils.class);
    private static final HttpClient client = HttpClientBuilder.create().build();


    /**
     * 获取图片字节流
     * @param uri
     * @return
     * @throws Exception
     */
    public static byte[] getByte(String uri) throws IOException {

        HttpGet get = new HttpGet(uri);
        try {
            HttpResponse resonse = client.execute(get);
            if (resonse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = resonse.getEntity();
                if (entity != null) {
                    return EntityUtils.toByteArray(entity);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new byte[0];
    }

    /**
     * 保存图片
     * @param domain 图片域名
     * @param fileName 带路径的文件名
     * @param destPath 保存路径
     * @return String 保存的相对路径
     * @throws IOException
     */
    public static String save(String domain, String fileName , String destPath) throws  IOException{
        int idx = fileName.indexOf("?");
        if(idx > 0){
            fileName = fileName.substring(0, idx);
        }
        File file = new File(destPath);
        if(!file.exists()){
            file.mkdir();
        }
        String [] arr = fileName.split("/");
        String realFileName = arr[arr.length -1];
        //创建图片目录
        if(arr.length > 1){
            String imageDir = destPath;
            for(int i=0;i<arr.length-1;i++){
                imageDir += "/" + arr[i];
                File dir = new File(imageDir);
                if(!dir.exists()){
                    dir.mkdir();
                }
            }
        }

        String filePath = destPath + fileName;
        BufferedOutputStream out = null;
        String url = domain + fileName;
        byte[] bit = getByte(url);
        if (bit.length > 0) {
            try {
                out = new BufferedOutputStream(new FileOutputStream(filePath));
                out.write(bit);
                out.flush();
                log.info("Create File success! [" + filePath + "]");
                return realFileName;
            } finally {
                if (out != null) {
                    out.close();
                }
            }
        }
        return null;
    }

    public static void main(String[] args) throws IOException {
        String url = "https://z1.muscache.cn/im/pictures/973eeb40-4b56-4ab9-810b-20b16f97726f.jpg?aki_policy=large";
        //HttpUtils.save(url, "");
    }
}
